package com.hzjy.api.service.impl;

import cn.tign.hz.helper.SignHelper;
import cn.tign.hz.helper.TokenHelper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzjy.api.beans.HzjyAgreement;
import com.hzjy.api.beans.HzjyDelist;
import com.hzjy.api.beans.HzjyProduct;
import com.hzjy.api.mapper.HzjyAgreementMapper;
import com.hzjy.api.service.BqTokenService;
import com.hzjy.api.vo.AgreementDTO;
import com.hzjy.api.vo.BqLoginUser;
import com.hzjy.api.vo.DelistListVO;
import com.hzjy.common.enums.DelistingStatusEnum;
import com.hzjy.common.enums.TradingStatusEnum;
import com.hzjy.common.enums.TradingType;
import com.hzjy.common.utils.JSONUtil;
import com.hzjy.common.utils.PageData;
import com.hzjy.common.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;


/**
 * 协议书，合同Service业务层处理
 *
 * @author hzjy
 * @date 2020-08-25
 */
@Service
public class HzjyAgreementServiceImpl {
    private static final Logger log = LoggerFactory.getLogger(HzjyAgreementServiceImpl.class);
    @Autowired
    private HzjyAgreementMapper hzjyAgreementMapper;
    @Autowired
    private ApiProductServiceImpl apiProductService;
    @Autowired
    private ApiDelistServiceImpl apiDelistService;
    @Autowired
    private BqTokenService bqTokenService;


    /**
     * 摘牌信息
     *
     * @return
     */
    public List<DelistListVO> delistList(PageData pd) {
        return hzjyAgreementMapper.delistList(pd);
    }

    /**
     * 查询协议书，合同
     *
     * @param id 协议书，合同ID
     * @return 协议书，合同
     */
    public HzjyAgreement selectHzjyAgreementById(Long id) {
        return hzjyAgreementMapper.selectHzjyAgreementById(id);
    }

    /**
     * 查询协议书，合同列表
     *
     * @param hzjyAgreement 协议书，合同
     * @return 协议书，合同
     */
    public List<HzjyAgreement> selectHzjyAgreementList(HzjyAgreement hzjyAgreement) {
        List<HzjyAgreement> hzjyAgreementList = hzjyAgreementMapper.selectMyHzjyAgreementList(hzjyAgreement);
        if (!CollectionUtils.isEmpty(hzjyAgreementList)) {
            for (HzjyAgreement hzjyAgreement1 : hzjyAgreementList) {
                if (hzjyAgreement1.getType() == 2) {
                    //摘牌
                    HzjyDelist hzjyDelist = apiDelistService.selectHzjyDelistById(hzjyAgreement1.getDelistId());
                    if (hzjyDelist != null) {
                        HzjyProduct hzjyProduct = apiProductService.selectProductInfo(Long.valueOf(hzjyAgreement1.getProductId()));
                        if (hzjyDelist.getStatus() == DelistingStatusEnum.Delivery.getCode()) {
                            if (hzjyProduct.getUserId() == Integer.parseInt(hzjyAgreement1.getSaleUserId())) {
                                hzjyAgreement1.setPickUpStatus(1);
                            }
                        } else if (hzjyDelist.getStatus() == DelistingStatusEnum.ConfirmCollection.getCode()) {
                            if (Integer.parseInt(hzjyDelist.getUserId()) == Integer.parseInt(hzjyAgreement1.getUserId()) && Integer.parseInt(hzjyAgreement1.getUserId()) != Integer.parseInt(hzjyAgreement1.getSaleUserId())) {
                                hzjyAgreement1.setPickUpStatus(2);
                            }
                        }
                    }
                }
                //当前登录的用户id
                if (ServletUtils.getRequestAttributes() != null) {
                    BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
                    hzjyAgreement1.setNowUserId(loginUser.getBqUser().getUserId().toString());
                }
            }
        }
        return hzjyAgreementList;
    }

    /**
     * 新增协议书，合同
     *
     * @param hzjyAgreement 协议书，合同
     * @return 结果
     */
    public int insertHzjyAgreement(HzjyAgreement hzjyAgreement) {
        return hzjyAgreementMapper.insertHzjyAgreement(hzjyAgreement);
    }

    /**
     * 修改协议书，合同
     *
     * @param hzjyAgreement 协议书，合同
     * @return 结果
     */
    public int updateHzjyAgreement(HzjyAgreement hzjyAgreement) {
        return hzjyAgreementMapper.updateHzjyAgreement(hzjyAgreement);
    }

    /**
     * 批量删除协议书，合同
     *
     * @param ids 需要删除的协议书，合同ID
     * @return 结果
     */
    public int deleteHzjyAgreementByIds(Long[] ids) {
        return hzjyAgreementMapper.deleteHzjyAgreementByIds(ids);
    }

    /**
     * 删除协议书，合同信息
     *
     * @param id 协议书，合同ID
     * @return 结果
     */
    public int deleteHzjyAgreementById(Long id) {
        return hzjyAgreementMapper.deleteHzjyAgreementById(id);
    }

    /**
     * 生成合同编号
     *
     * @param gOrZ        1 : G ,0: Z
     * @param productType 1 : P ; 0 : W
     * @param year
     * @param number
     * @return
     */
    public String createContractNo(int gOrZ, int productType, int year,
                                   int number) {
//        String comp = ChineseCharacterUtil.getFirstSpell(companyName).toUpperCase();
        String contractNo = "CCCT" + (gOrZ == 1 ? TradingType.G.getInfo() : TradingType.Z.getInfo()) +
                (productType == 1 ? TradingType.P.getInfo() : TradingType.W.getInfo()) + year + number;
        log.info("生成的合同编号为:" + contractNo);
        return contractNo;
    }

    /**
     * E签宝签合同回调关闭流程
     *
     * @param flowId
     */
    @Transactional
    public void closeContract(String flowId) throws Exception {
        HzjyAgreement queryContract = new HzjyAgreement();
        queryContract.setFlowId(flowId);
        List<HzjyAgreement> hzjyAgreementList = hzjyAgreementMapper.selectHzjyAgreementList(queryContract);
        if (CollectionUtils.isEmpty(hzjyAgreementList)) {
            log.error("根据E签宝流程ID查询合同信息异常.");
            return;
        }
        HzjyAgreement hzjyAgreement = hzjyAgreementList.get(0);
        hzjyAgreement.setStatus(1);
        hzjyAgreement.setContractUrl(downContractFromEQB(hzjyAgreement.getFlowId()));
        hzjyAgreementMapper.updateHzjyAgreement(hzjyAgreement);
        if (hzjyAgreement.getType() == 1) {
            //更新挂牌状态为协议签订完成
            HzjyProduct hzjyProduct = apiProductService.selectProductInfo(Long.valueOf(hzjyAgreement.getProductId()));
            hzjyProduct.setState(TradingStatusEnum.SignCompleted.getCode());
            apiProductService.updateHzjyProduct(hzjyProduct);
        } else if (hzjyAgreement.getType() == 2) {
            //更新摘牌状态为协议签订完成
            HzjyDelist hzjyDelist = apiDelistService.selectHzjyDelistById(hzjyAgreement.getDelistId());
            log.info("-----------查询的摘牌数据-------------------"+ JSONUtil.bean2json(hzjyDelist));
            if (hzjyDelist.getStatus() == 54){
                //当摘牌方已经付完款
                hzjyDelist.setStatus(DelistingStatusEnum.Delivery.getCode());
            }else {
                hzjyDelist.setStatus(DelistingStatusEnum.TradeAndDelistDelivery.getCode());
            }
            apiDelistService.updateHzjyDelist(hzjyDelist);
        }
    }

    /**
     * 从E签宝拉取合同
     *
     * @param flowId
     * @return
     * @throws Exception
     */
    public String downContractFromEQB(String flowId) throws Exception {
        log.info("从E签宝拉取合同.................");
        log.info("---------------------获取token start------------------------------");
        //设置token缓存
        TokenHelper.getTokenData();
        JSONObject jsonObject = SignHelper.downloadFlowDoc(flowId);
        log.info("---------------------回调从E签宝下载合同-------------------------------" + jsonObject.toString());
        Map mp = JSON.parseObject(jsonObject.toString());
        JSONObject docs = (JSONObject) mp.get("data");
        JSONArray jsonArray = docs.getJSONArray("docs");
        log.info("=====docs====" + docs.toString());
        if (!CollectionUtils.isEmpty(docs)) {
            JSONObject doc = jsonArray.getJSONObject(0);
            log.info("=====doc====" + doc.toString());
            log.info("=====fileUrl=====" + doc.get("fileUrl"));
            return doc.get("fileUrl").toString();
        } else {
            throw new Exception();
        }
    }

    /**
     * wx合同列表
     * @param pageData
     * @return
     */
    public List<PageData> queryHzjyAgreementList(PageData pageData) {
        List<PageData> pageDataList = hzjyAgreementMapper.queryMyHzjyAgreementList(pageData);
        if (!CollectionUtils.isEmpty(pageDataList)) {
            for (PageData newPageData : pageDataList) {
                if (Integer.parseInt(newPageData.get("type").toString()) == 2) {
                    //摘牌
                    HzjyDelist hzjyDelist = apiDelistService.selectHzjyDelistById(Long.parseLong(newPageData.get("delist_id").toString()));
                    if (hzjyDelist != null) {
                        HzjyProduct hzjyProduct = apiProductService.selectProductInfo(Long.parseLong(newPageData.get("product_id").toString()));
                        if (hzjyDelist.getStatus() == DelistingStatusEnum.PaySuccess.getCode()) {
                            if (hzjyProduct.getUserId() == Integer.parseInt(newPageData.get("sale_user_id").toString())) {
                                newPageData.put("pickUpStatus",1);
                            }
                        } else if (hzjyDelist.getStatus() == DelistingStatusEnum.ConfirmCollection.getCode()) {
                            if (Integer.parseInt(hzjyDelist.getUserId()) == Integer.parseInt(newPageData.get("user_id").toString())) {
                                newPageData.put("pickUpStatus",2);
                            }
                        }
                    }
                }
                //当前登录的用户id
                if (ServletUtils.getRequestAttributes() != null) {
                    BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
                    newPageData.put("nowUserId",loginUser.getBqUser().getUserId().toString());
                }
            }
        }
        return pageDataList;
    }

    /**
     * 查询合同列表总条数
     * @param pageData
     * @return
     */
    public PageData getAgreementNum(PageData pageData) {
        PageData pd = hzjyAgreementMapper.getAgreementNum(pageData);
        return pd;
    }

    /**
     * 后台查询合同列表
     * @param agreementDTO
     * @return
     */
    public List<AgreementDTO> selectAgreementList(AgreementDTO agreementDTO) {
        return hzjyAgreementMapper.selectAgreementList(agreementDTO);
    }

    /**
     * 后台查询合同列表总条数
     * @param agreementDTO
     * @return
     */
    public Integer selectAgreementNum(AgreementDTO agreementDTO) {
        return hzjyAgreementMapper.selectAgreementNum(agreementDTO);
    }
}
